<template>
  <div class="container">
    <!-- 新增商品按钮 -->
    <el-button type="primary" @click="showDialog" class="mb-20">新增商品</el-button>

    <!-- 商品表格 -->
    <el-table :data="goodsList" style="width: 100%" border stripe
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
      <el-table-column prop="id" label="商品编号" width="100" align="center" />
      <el-table-column prop="name" label="商品名称" width="150" />
      <el-table-column prop="price" label="商品价格" width="120" align="center">
        <template #default="{ row }">¥{{ row.price }}</template>
      </el-table-column>
      <el-table-column prop="stock" label="商品库存" width="120" align="center" />
      <el-table-column prop="desc" label="商品简介" min-width="200" />
      <el-table-column prop="shopName" label="商铺名字" width="150" /> <!-- 新增商铺名字列 -->
      <el-table-column label="商品图片" width="120" align="center">
        <template #default="{ row }">
          <img :src="row.image" class="product-image" @click="handlePreview(row.image)">
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editGoods(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="deleteGoods(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 商品表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="formTitle" width="600px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="formData" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商铺名字" prop="shopName">
              <el-input v-model="formData.shopName" placeholder="请输入商铺名字" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number v-model="formData.price" :min="0" :precision="2" controls-position="right"
                class="full-width" placeholder="请输入价格" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="formData.category" placeholder="请选择分类" class="full-width">
                <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input-number v-model="formData.stock" :min="0" controls-position="right" class="full-width"
                placeholder="请输入库存" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="简介" prop="desc">
          <el-input v-model="formData.desc" type="textarea" :rows="3" placeholder="请输入商品简介" show-word-limit
            maxlength="200" />
        </el-form-item>

        <!-- 图片上传区域 -->
        <el-form-item label="图片" prop="image">
          <div class="upload-area">
            <input type="file" ref="fileInput" accept="image/*" @change="handleFileSelect" hidden>
            <div class="upload-box" @click="$refs.fileInput.click()">
              <div v-if="previewImage" class="preview-container">
                <img :src="previewImage" class="preview-image">
                <div class="file-size-tip">{{ fileSize }}</div>
              </div>
              <div v-else class="upload-placeholder">
                <el-icon :size="24">
                  <Plus />
                </el-icon>
                <div class="upload-text">上传图片</div>
              </div>
            </div>
            <div class="upload-tip">支持JPG/PNG格式，大小不超过500KB</div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false" size="small">取消</el-button>
        <el-button type="primary" @click="submitForm" size="small">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useShopStore } from '@/stores/shopStore'

import axios from 'axios'

// 在组件中添加用户登录逻辑
const shopStore = useShopStore()

// 获取当前用户
const getCurrentUser = () => {
  return JSON.parse(localStorage.getItem("currentUser"))
}

// 设置当前用户（登录时调用）
const login = (user) => {
  shopStore.setCurrentUser(user)
}

// 登出
const logout = () => {
  localStorage.removeItem("currentUser")
  shopStore.setCurrentUser(null)
  resetForm()
}
// 示例用户数据
const users = [
  { id: "user1", username: "seller1", password: "123456", role: "seller" },
  { id: "user2", username: "seller2", password: "123456", role: "seller" }
]

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 登录函数
const handleLogin = () => {
  const user = users.find(u =>
    u.username === loginForm.username &&
    u.password === loginForm.password
  )

  if (user) {
    login(user)
    ElMessage.success('登录成功')
  } else {
    ElMessage.error('用户名或密码错误')
  }
}

// 修改商品列表获取方式
const goodsList = computed(() => shopStore.getCurrentUserGoods().map(item => ({
  ...item,
  shopName: item.shopName || ''
})))
// 对话框状态
const dialogVisible = ref(false)
const formTitle = ref('新增商品')
const formData = reactive({
  id: null,
  name: '',
  price: 0,
  desc: '',
  category: '',
  stock: 0,
  image: null,
  shopName: ''  // 新增商铺名字字段
})

// 图片上传相关
const fileInput = ref(null)
const previewImage = ref(null)
const selectedFile = ref(null)
const categories = [
  { value: '1', label: '电子产品' },
  { value: '2', label: '服装鞋帽' },
  { value: '3', label: '食品' },
  { value: '4', label: '娱乐' },
  { value: '5', label: '物品' }
]

// 显示对话框
const showDialog = () => {
  resetForm()
  formTitle.value = '新增商品'
  dialogVisible.value = true
}

// 处理文件选择
const handleFileSelect = (e) => {
  const file = e.target.files[0]
  if (!file) return

  if (file.size > 500 * 1024) {
    ElMessage.error('图片大小不能超过500KB')
    return
  }

  selectedFile.value = file

  const reader = new FileReader()
  reader.onload = () => {
    previewImage.value = reader.result
  }
  reader.readAsDataURL(file)
}

// 提交表单
const submitForm = () => {
  if (!validateForm()) return;

  const goodsData = {
    ...formData,
    image: previewImage.value // 直接使用base64字符串
  };

  let newGoodEntry;

  if (formData.id) {
    // 编辑商品
    shopStore.updateGoods(goodsData);
    ElMessage.success('商品更新成功');
  } else {
    // 新增商品
    const newId = Math.random().toString(36).substr(2, 6);
    // 不再生成图片URL，直接使用base64字符串
    const newGoods = {
      ...goodsData,
      id: newId,
      // image: imageUrl   // 不再使用imageUrl
      image: previewImage.value // 使用base64
    };

    shopStore.addGoods(newGoods);
    ElMessage.success('商品添加成功');

    // 构建符合db.json格式的商品条目
    newGoodEntry = {
      userId: getCurrentUser(),
      id: newId,
      name: newGoods.name,
      price: newGoods.price,
      type: categories.find(cat => cat.value === newGoods.category)?.label || '未知分类',
      // image_url: imageUrl   // 改为base64字符串
      image_url: previewImage.value, // 直接存储base64字符串
      stock_quantity: newGoods.stock,
      shopName: newGoods.shopName  // 新增商铺名字字段
    };
  }

  dialogVisible.value = false;

  if (newGoodEntry) {
    axios.post('http://localhost:3000/products', newGoodEntry)
      .then(response => {
        console.log('商品已添加至db.json:', response.data);
      })
      .catch(error => {
        console.error('保存商品失败:', error);
        ElMessage.error('商品保存失败');
      });
  }
};

// 表单验证
const validateForm = () => {
  if (!formData.name.trim()) {
    ElMessage.error('请输入商品名称')
    return false
  }
  if (!selectedFile.value && !formData.image) {
    ElMessage.error('请选择商品图片')
    return false
  }
  return true
}

// 预览大图
const handlePreview = (url) => {
  ElMessageBox.alert(`<img src="${url}" style="max-width: 100%">`, '图片预览', {
    dangerouslyUseHTMLString: true,
    customClass: 'preview-dialog'
  })
}

// 删除商品
const deleteGoods = (id) => {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 1. 从Vuex商店删除商品
    shopStore.deleteGoods(id)

    // 2. 从db.json删除商品数据
    axios.delete(`http://localhost:3000/products/${id}`)
      .then(() => {
        // 3. 删除相关订单数据（如果需要）
        axios.get(`http://localhost:3000/orders?productId=${id}`)
          .then(res => {
            res.data.forEach(order => {
              axios.delete(`http://localhost:3000/orders/${order.id}`)
            })
          })

        // 4. 删除收藏数据（如果需要）
        axios.get(`http://localhost:3000/favorites?productId=${id}`)
          .then(res => {
            res.data.forEach(favorite => {
              axios.delete(`http://localhost:3000/favorites/${favorite.id}`)
            })
          })

        ElMessage.success('商品删除成功')
      })
      .catch(error => {
        console.error('删除商品失败:', error)
        ElMessage.error('商品删除失败')
      })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 编辑商品
const editGoods = (row) => {
  Object.assign(formData, {
    ...row,
    shopName: row.shopName // 确保加载 shopName 字段
  });
  previewImage.value = row.image;
  formTitle.value = '编辑商品';
  dialogVisible.value = true;
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    price: 0,
    desc: '',
    category: '',
    stock: 0,
    image: null,
    shopName: ''  // 重置 shopName 字段
  });
  previewImage.value = null;
  selectedFile.value = null;
}

// 计算文件大小
const fileSize = computed(() => {
  if (!selectedFile.value) return '';
  return `${(selectedFile.value.size / 1024).toFixed(1)}KB`;
})
</script>

<style scoped>
.container {
  padding: 20px;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}

.mb-20 {
  margin-bottom: 20px;
}

.product-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  cursor: zoom-in;
  border: 1px solid #ebeef5;
}

.upload-area {
  width: 100%;
}

.upload-box {
  width: 160px;
  height: 160px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background-color: #fafafa;
  transition: border-color .3s;
}

.upload-box:hover {
  border-color: #409eff;
}

.upload-placeholder {
  text-align: center;
  color: #8c939d;
}

.upload-text {
  margin-top: 8px;
  font-size: 12px;
}

.preview-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.file-size-tip {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 4px;
  background: rgba(0, 0, 0, .5);
  color: #fff;
  font-size: 12px;
  text-align: center;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}

:deep(.el-dialog__body) {
  padding: 20px 25px;
}

:deep(.el-form-item__label) {
  color: #606266;
}

.full-width {
  width: 100%;
}
</style>